package com.itheima.exception;


import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice//全局异常处理器，把方法的返回值转为json格式返回给前端
public class GlobalExceptionHandler {

    //处理异常
    @ExceptionHandler
    public Result ex(Exception e){
        log.error("发生未知异常",e);
        //捕获到异常之后，响应一个标准的Result
        return Result.error("服务器异常");
    }
    @ExceptionHandler
    public Result handleArrayIndexOutofBoundException(ArrayIndexOutOfBoundsException exception){
        log.error("数组越界异常",exception);
        return Result.error("数组越界异常");
    }

    @ExceptionHandler(ArithmeticException.class)//指定要捕获的异常类型
    public Result handleArithmeticException(ArithmeticException e){
        log.error("算术异常",e);
        return Result.error("算术异常");
    }


    @ExceptionHandler(DuplicateKeyException.class)//重复添加异常
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("数据已存在",e);
        String message = e.getCause().getMessage();
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");//按空格键进行分割
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }
        return Result.error("操作失败");
    }
    /**
     * 参数校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException e){
        //获取校验没通过的属性和错误信息
        //所有校验没有通过的属性
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringJoiner joiner = new StringJoiner(",");//拼接器，以逗号进行拼接
        for (FieldError fieldError : fieldErrors){
            //没通过校验的属性名
            String field = fieldError.getField();
            //没通过校验的错误信息
            joiner.add(fieldError.getDefaultMessage());
            log.info(field + ":" + fieldError.getDefaultMessage());
        }
        return Result.error(joiner.toString());
    }
}